import Taro from '@tarojs/taro'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import { Text } from '@tarojs/components'

import AtComponent from '../../common/component'

export default class AtIcon extends AtComponent {
  static defaultProps = {
    customStyle: {},
    className: '',
    prefixClass: 'at-icon',
    value: '',
    type: '',
    color: '',
    onClick: () => {}
  }

  static propTypes = {
    customStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
    className: PropTypes.oneOfType([PropTypes.array, PropTypes.string]),
    prefixClass: PropTypes.string,
    value: PropTypes.string,
    type: PropTypes.string,
    color: PropTypes.string,
    spin: PropTypes.bool,
    size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    onClick: PropTypes.func
  }

  constructor () {
    super(...arguments)
    if (process.env.NODE_ENV === 'test') {
      Taro.initPxTransform({ designWidth: 750 })
    }
  }

  handleClick () {
    this.props.onClick(...arguments)
  }

  render () {
    const { customStyle, className, prefixClass, value, type, size, color, spin } = this.props
    const rootStyle = {
      color
    }
    if (size) {
      rootStyle.fontSize = Number.isNaN(parseInt(size))
        ? size
        : `${Taro.pxTransform(parseInt(size) * 2)}`
    }
    const typeNow = type || value
    const iconName = typeNow ? `${prefixClass}-${typeNow}` : ''
    const spinClass = {
      [`${prefixClass}-spin`]: spin === false ? spin : spin || typeNow.indexOf('loading') !== -1
    }
    return (
      <Text
        className={classNames(prefixClass, iconName, className, spinClass)}
        style={this.mergeStyle(rootStyle, customStyle)}
        onClick={this.handleClick.bind(this)}
      />
    )
  }
}
